<?php
//FALTA ADAPTAR LA FUNCIÓN !!!!
$ip = $_SERVER['REMOTE_ADDR'];
$login = NULL;
$userdata = NULL;

// Returns whether the connected user is logged in, sets $login, $teamdata
function logged_in()
{
	global $DB, $ip, $login, $userdata;
	print_r($userdata);
	echo $login;

	if ( !empty($login) && !empty($userdata) ) return TRUE;

	// Retrieve teamdata for given AUTH_METHOD, assume not logged in
	// when teamdata is empty:
	session_start();
	if ( isset($_SESSION['userid']) ) {
		/*$userdata = $DB->q('MAYBETUPLE SELECT * FROM team WHERE login = %s',
			           $_SESSION['teamid']);*/
		$conexion = connect();
		$query = "SELECT * FROM users WHERE username = '".$_SESSION['userid']."'";
		$res = mysql_query($query, $conexion) or die(mysql_error());
		$userdata = mysql_fetch_array($res, MYSQL_NUM);
		//print_r($userdata);
	}

	if ( !empty($userdata) ) {
		$login = $userdata[0];
		// is this the first visit? record that in the team table
		if ( empty($row['teampage_first_visited']) ) {
			$hostname = gethostbyaddr($ip);
			//posible nuevo campo
			/*$DB->q('UPDATE team SET teampage_first_visited = %s, hostname = %s
			        WHERE login = %s',
			       now(), $hostname, $login);*/
		}
	}
	//echo $login;
	return $login!==NULL;
}

// Returns whether the active authentication method has logout functionality.
function have_logout()
{
	switch ( AUTH_METHOD ) {
	case 'FIXED':        return FALSE;
	case 'IPADDRESS':    return FALSE;
	case 'PHP_SESSIONS': return TRUE;
	}
	return FALSE;
}

// Generate a page stating that login has failed with $msg and exit.
function show_failed_login($msg)
{
	$title = 'Login failed';
	$menu = false;
	require(LIBWWWDIR . '/header.php');
	echo "<h1>Not Authenticated</h1>\n\n<p>$msg</p>\n\n";
	require(LIBWWWDIR . '/footer.php');
	exit;
}

/// This function presents some kind of login page, which should e.g.
// have a POST form to supply login credentials. This function does
// not return.
function show_loginpage(){
global $ip;

if ( NONINTERACTIVE ) error("Not authenticated");
$title = 'Not Authenticated';
//$menu = true;
//include(LIBWWWDIR . '/header.php'); 
// **************** header ****************//
// ****el siguiente código reemplaza a include(LIBWWWDIR . '/header.php');
if (!defined('DOMJUDGE_VERSION')) die("DOMJUDGE_VERSION not defined.");

header('Content-Type: text/html; charset=' . DJ_CHARACTER_SET);

if ( isset($refresh) ) {
	header('Refresh: ' . $refresh);
}
echo '<?xml version="1.0" encoding="' . DJ_CHARACTER_SET . '" ?>' . "\n";

if(!isset($ajaxtitle)) {
	$ajaxtitle = '';
}?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<!-- DOMjudge version <?php echo DOMJUDGE_VERSION?> -->
<title><?php echo $title?></title>
<link rel="shortcut icon" href="../images/favicon.png" type="image/png" />
<link rel="stylesheet" href="../style.css" type="text/css" />
<script type="text/javascript" src="../js/domjudge.js"></script>
</head>
<body onload="setInterval('updateClarifications(\'<?php echo $ajaxtitle?>\')', 20000)">
<!--menu -->
<div id="menutop">
<a href="../public/" accesskey="s">scoreboard</a>
<a href="../public/info.php" accesskey="i">information</a>
<a href="index.php" accesskey="l">login</a>
<a href="" accesskey="f">forgot password</a>
<a href="../register/register.php" accesskey="r">register</a>
<br><a href="../inscripciones/">Inscripciones a contest actuales</a>
<br><a href="../gene_usu/">Solicitar cuenta Postmaratón</a>
</div>
<!-- // **************** header ****************// -->

<h1>Not Authenticated</h1>

<p>Sorry, we are unable to identify you as a valid user
(IP <?php echo htmlspecialchars($ip); ?>).</p>

<p>
Please supply user credentials below, or contact a staff member for assistance.
</p>

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<table>
<input type="hidden" name="cmd" value="login" />
<tr><td><label for="login">Login:</label></td><td><input type="text" id="login" name="login" value="" size="15" maxlength="15" accesskey="l" /></td></tr>
<tr><td><label for="passwd">Password:</label></td><td><input type="password" id="passwd" name="passwd" value="" size="15" maxlength="255" accesskey="p" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Login" /></td></tr>
</table>
</form>

<?php
putDOMjudgeVersion();
include(LIBWWWDIR . '/footer.php');

exit;
}
// Try to login a team with e.g. authentication data POST-ed. Function
// does not return and should generate e.g. a redirect back to the
// referring page.
function do_login()
{
	global $DB, $ip, $login, $userdata;

	$user = trim($_POST['login']);
	$pass = trim($_POST['passwd']);
	$title = 'Authenticate user';
	$menu = false;

	if ( empty($user) || empty($pass) ) {
		show_failed_login("Please supply a username and password.");
	}

	/*$userdata = $DB->q('MAYBETUPLE SELECT * FROM users
		           WHERE username = %s AND password = %s',
		           $user, md5($pass));*/
	$conexion = connect();
	$query = "SELECT * FROM users WHERE username = '".$user ."' AND password = '".md5($pass)."'";
	$res = mysql_query($query, $conexion) or die(mysql_error());
	$userdata = mysql_fetch_array($res, MYSQL_NUM);

	if ( !$userdata ) {
		sleep(3);
		show_failed_login("Invalid username or password supplied. " .
			                  "Please try again or contact a staff member.");
	}

	$login = $userdata['0'];
	session_start();
	$_SESSION['userid'] = $login;

	require(LIBWWWDIR . '/header.php');
	echo "<h1>Authenticated</h1>\n\n<p>Successfully authenticated as user " .
	    htmlspecialchars($login) . " on " . htmlspecialchars($ip) . ".</p>\n" .
	    "<p><a href=\"$_SERVER[PHP_SELF]\">Continue to your team page $_SERVER[PHP_SELF] </a>, " .
	    "and good luck!</p>\n\n";
	require(LIBWWWDIR . '/footer.php');

	exit;
}


function do_logout()
{
	global $DB, $ip, $login, $userdata;

	switch ( AUTH_METHOD ) {
	case 'PHP_SESSIONS':
		// Unset all of the session variables.
		$_SESSION = array();
			
		// Also delete the session cookie.
		if ( ini_get("session.use_cookies") ) {
			$params = session_get_cookie_params();
			setcookie(session_name(), '', time() - 42000,
			          $params["path"], $params["domain"],
			          $params["secure"], $params["httponly"]);
		}

		// Finally, destroy the session.
		if ( !session_destroy() ) error("PHP session not successfully destroyed.");
		break;

	default:
		error("Unknown authentication method '" . AUTH_METHOD .
		      "' requested, or logout not supported.");
	}

	$title = 'Logout';
	$menu = FALSE;

	require(LIBWWWDIR . '/header.php');
	echo "<h1>Logged out</h1>\n\n<p>Successfully logged out as user " .
	    htmlspecialchars($login) . ".</p>\n" .
	    "<p><a href=\"./\">Click here to login again.</a></p>\n\n";
	require(LIBWWWDIR . '/footer.php');
	exit;
}
?>
